package center_rpc

import (
	"common/macaroon"
	"common/pb"
	rpc2 "common/rpc"
	"context"
	"github.com/zeebo/errs"
	"go.uber.org/zap"
	"net"
	"storj.io/drpc/drpcconn"
	"time"
)

var Error = errs.Class("cRPC")

type CenterRpc struct {
	addr    string
	apiKey  *macaroon.APIKey
	dialer  *rpc2.TcpDialer
	conn    net.Conn
	log     *zap.Logger
	timeout time.Duration //调用超时时间
}

func NewClient(ctx context.Context, addr string, apiKey *macaroon.APIKey, dialer *rpc2.TcpDialer, log *zap.Logger) *CenterRpc {
	cRpc := &CenterRpc{addr: addr, apiKey: apiKey, dialer: dialer, conn: nil, log: log}
	if cRpc.timeout == 0 {
		cRpc.timeout = time.Second * 10
	}
	return cRpc
}

// Header 用于鉴权
func (cRpc *CenterRpc) Header() *pb.RequestHeader {
	return &pb.RequestHeader{ApiKey: cRpc.apiKey.SerializeRaw()}
}

func (cRpc *CenterRpc) getDrpcClient(ctx context.Context) (pb.DRPCMetainfoClient, func() error, error) {
	c, err := cRpc.dialer.DialTLS(ctx, cRpc.addr)
	if err != nil {
		return nil, nil, err
	}
	// convert the net.Conn to a drpc.Conn
	conn := drpcconn.New(c)
	return pb.NewDRPCMetainfoClient(conn), func() error {
		return conn.Close()
	}, nil
}
